package com.briup.srms.sms.service.impl;

import java.util.Date;
import java.util.List;

import com.briup.srms.sms.bean.Student;
import com.briup.srms.sms.bean.StudentExample;
import com.briup.srms.sms.dao.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.briup.srms.sms.bean.Clazz;
import com.briup.srms.sms.bean.extend.ClazzExtend;
import com.briup.srms.sms.dao.ClazzMapper;
import com.briup.srms.sms.dao.extend.ClazzExtendMapper;
import com.briup.srms.sms.service.IClazzService;
import com.jacky.base.utils.CustomerException;
import com.jacky.base.utils.PageVM;

@Service
public class ClazzServiceImpl implements IClazzService {

	@Autowired
	private ClazzMapper clazzMapper;
	@Autowired
	private ClazzExtendMapper clazzExtendMapper;

	@Autowired
	private StudentMapper studentMapper;

	@Override
	public PageVM<ClazzExtend> pageQueryFull(int page, int pageSize, String year, Long directionId,String area,String status,Long chargeId) {
		List<ClazzExtend> list = clazzExtendMapper.queryFull(page, pageSize,year,directionId,area,status,chargeId);
		long total = clazzExtendMapper.count(year,directionId,area,status,chargeId);
		return new PageVM<>(page, pageSize, total, list);
	}

	@Override
	public PageVM<Clazz> pageQuery(int page, int pageSize,String year,Long directionId,String area,String status,Long chargeId) {
		List<Clazz> list = clazzExtendMapper.query(page, pageSize,year,directionId,area,status,chargeId);
		long total = clazzExtendMapper.count(year,directionId,area,status,chargeId);
		return new PageVM<>(page, pageSize, total, list);
	}
	@Override
	public void saveOrUpdate(Clazz clazz) {
		if(clazz.getId() == null) {
			clazz.setCreateTime(new Date().getTime());
			clazz.setLeaveNum(0);
			clazz.setStatus(ClazzExtend.STATUS_NOT_BEGIN);
			clazzMapper.insert(clazz);
		} else {
			clazzMapper.updateByPrimaryKey(clazz);
		}
	}

	@Override
	public void startClazz(Clazz clazz) {
		clazz.setStatus("正常");
		clazzMapper.updateByPrimaryKey(clazz);
	}

	@Override
	public void deleteById(long id) {
		Clazz dict = clazzMapper.selectByPrimaryKey(id);
		if(dict == null) {
			throw new CustomerException("要删除的数据不存在");
		}
        /**
         * time: 2022-03-17
         * 删除班级时判断该班级是否有学生，如果有则不允许删除。
         */
        StudentExample ex = new StudentExample();
        ex.createCriteria().andClazzIdEqualTo(id);
        List<Student> list = studentMapper.selectByExample(ex);
        if (list == null || list.size() == 0)
            clazzMapper.deleteByPrimaryKey(id);
        else
            throw new CustomerException("无法删除非空班级！");
	}
	@Override
	public void finishClazz(long id) {
		Clazz clazz = clazzMapper.selectByPrimaryKey(id);
		clazz.setStatus(ClazzExtend.STATUS_FINISHED);
		clazzMapper.updateByPrimaryKey(clazz);
	}
}
